package com.maxima.maximaAttendance.reports;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtils {

	public static File createZip(List<File> reportFiles, File targetFile)
			throws IOException {
		if (!targetFile.exists()) {
			targetFile.createNewFile();
		}
		FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
		ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);

		for (File file : reportFiles) {
			addToZipFile(file, zipOutputStream);
		}
		zipOutputStream.close();
		fileOutputStream.close();
		return null;
	}

	public static void addToZipFile(File file, ZipOutputStream zos)
			throws IOException {

		FileInputStream fis = new FileInputStream(file);
		String filename = file.getName();
		if (filename.lastIndexOf("\\") > -1) {
			filename = filename.substring(filename.lastIndexOf("\\") + 1);
		}
		if (filename.lastIndexOf("/") > -1) {
			filename = filename.substring(filename.lastIndexOf("/") + 1);
		}
		ZipEntry zipEntry = new ZipEntry(filename);
		zos.putNextEntry(zipEntry);

		byte[] bytes = new byte[1024];
		int length;
		while ((length = fis.read(bytes)) >= 0) {
			zos.write(bytes, 0, length);
		}

		zos.closeEntry();
		fis.close();
	}
}
